<?php

require_once('jhtraq.php');
class JhtraqModelWiki extends JhtraqModelJhtraq
{
	
	function createDefault($project_id)
	{
		$user =& JFactory::getUser();
		$created = $user->id;
		$this->db->setQuery("Insert into #__jhtraq_wiki set project_id=$project_id,page_name='Main_Page',version=1,created='".time()."',modified=0,created_by='$created',modified_by=0,body='".JText::_('COM_JHTRAQ_DEFAULT_WIKI_TEXT')."',hits=0");
		return $this->db->query();
	}
	
	function get($page,$version,$pid)
	{
		$query = "select * from #__jhtraq_wiki where project_id=$pid and page_name like'%" . $this->db->getEscaped($page) . "%'";
		if((int)$version > 0)
		$query .= " and version='$version' ";
		$query .= " order by version desc limit 1";
		$this->db->setQuery($query);
		return $this->db->loadObject();
	}
	
	function hit($page,$pid)
	{
		$query = "Update #__jhtraq_wiki set hits=hits+1 where project_id=$pid and page_name like'%" . $this->db->getEscaped($page) . "%'";
		$this->db->setQuery($query);
		return $this->db->query();
	}
	
	function save($wiki,$post,$pid)
	{
		$user =& JFactory::getUser();
		$wiki->version++;
		$wiki->project_id = $pid;
		$wiki->body = addslashes($post['body']);
		$wiki->page_name = $this->db->getEscaped($post['page_name']);
		if($wiki->id > 0)
		{
			$wiki->modified_by = $user->id;
			$wiki->modified = time();
			$timeline = "edit_wikipage";
		}else{
			$wiki->created_by = $user->id;
			$wiki->created = time();
			$timeline = "create_wikipage";
		}
		$this->db->setQuery("Insert into #__jhtraq_wiki set project_id='{$wiki->project_id}',page_name='{$wiki->page_name}',version='{$wiki->version}',created='{$wiki->created}',modified='{$wiki->modified}',created_by='{$wiki->created_by}',modified_by='{$wiki->modified_by}',body='{$wiki->body}',hits='{$wiki->hits}'");
		$this->db->query();
		
		$username = ($user->username)?$user->username:JText::_('Guest');
		
		//This needs to be moved out of here and placed in the correct class file!!!!
		//TODO::: NBNBNB
		$this->db->setQuery("insert into #__jhtraq_timeline set project_id='{$wiki->project_id}',owner_id='{$user->id}',action='$timeline',data='{$wiki->page_name}',user_id='{$user->id}',user_name='$username',timestamp='".time()."',date='".DATE("Y-m-d")."'");
		$this->db->query();
		return $wiki;
	}
	
}